package encoding;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * 演示请求编码
 */
public class RequestEncoding extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //浏览器对查询字符会进行 UTF-8 编码，但是 tomcat 默认会使用 ISO-8859-1 进行解码，所以肯定会乱码
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        System.out.println(name + " : " + password);

        //解决方法是，获得原始的字节数组，然后手动转换
        byte[] bytes = name.getBytes("ISO-8859-1");
        name = new String(bytes, "UTF-8");
        System.out.println(name);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // post请求的参数都使用页面的 charset 进行 URL 编码过的
        // 所以要设置解码方式与页面的编码方式相同
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");

        System.out.println(name + " : " + password);
    }
}
